package org.oschina.api.user.menu.service;

import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.user.menu.dao.UserMenuDAO;
import org.oschina.api.user.menu.model.UserMenu;
import org.oschina.api.user.menu.vo.UserMenuVo;
import org.oschina.api.user.user.model.User;
import org.oschina.api.user.user.service.UserService;
import org.oschina.bean.Result;
import org.oschina.api.index.service.IndexService;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserMenuService extends BaseService {

	@Autowired
	private UserMenuDAO menuDAO;
	@Autowired
	private UserMenuRoleService menuRoleService;
	@Autowired
	private UserService userService;
	@Autowired
	private IndexService indexService;
	
	/**
	 * 返回
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public List<UserMenuVo> findVo()
	{
		return menuDAO.findVo();
	}
	
	/**
	 * 根据角色返回
	 * @param role
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public List<UserMenuVo> findVoByRole(int role)
	{
		return _findVoByRole(role);
	}
	
	/**
	 * 更新
	 * @param menu
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public Result update(UserMenu menu)
	{
		menuDAO.update(menu);
		return ResultUtil.getSuccess(menu);
	}
	
	/**
	 * 创建
	 * @param menu
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public Result create(UserMenu menu)
	{
		menu.setId(_getIndex());
		menu.setCreate_time(DateUtil.now());
		menuDAO.create(menu);
		return ResultUtil.getSuccess(menu);
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public Result delete(int id)
	{
		if(menuDAO.delete(id)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		menuRoleService._removeByMenu(id);
		return ResultUtil.getSuccess(Message.DELETE_SUCCESS);
	}
	
	/**
	 * 根据用户返回
	 * @return
	 */
	public List<UserMenuVo> findVoByUser()
	{
		User user=userService.getAuthenticationInfo(getToken());
		if(user==null)
			return null;

		return _findVoByRole(user.getRole());
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public UserMenuVo _findVoById(int id)
	{
		return menuDAO.findVoById(id);
	}
	
	/**
	 * 根据权限返回
	 * @param role
	 * @return
	 */
	private List<UserMenuVo> _findVoByRole(int role)
	{
		return menuDAO.findVoByRole(role);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_USER_MENU);
	}
}